package yxy.game.pm2.command.office;

import yxy.cherry.data.DataCenter;
import yxy.cherry.data.bean.conscriptldate;
import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.bean.currency.CurrencyNotEnoughException;
import yxy.game.pm2.bean.mq.CCReason;
import yxy.game.pm2.bean.task.TaskType;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.OfficeMessage;
import yxy.game.pm2.module.CurrencyHandle;
import yxy.game.pm2.module.office.OfficeHandle;
import yxy.game.pm2.module.office.OfficeModule;
import yxy.game.pm2.module.task.TaskHandle;

import java.util.ArrayList;

/** 主公府 主公府拜将 */
@MessageType(proto = Command.OfficeSummon, classtype = OfficeMessage.OfficeSummonRequest.class)
public class CMD_OfficeSummon extends Command<OfficeMessage.OfficeSummonRequest> {

	@Override
	public void execute(MessageSource messageSource, OfficeMessage.OfficeSummonRequest request) {
		String playerCode = messageSource.getTag();
		int type = request.getType();

		OfficeMessage.OfficeSummonResponse.Builder response = OfficeMessage.OfficeSummonResponse.newBuilder();

		OfficeModule officeModule = OfficeModule.get(playerCode);
		if (officeModule == null) {
			send(messageSource, response, Result.ModuleNotOpen);// 模块未开启
			return;
		}
		conscriptldate costdata = DataCenter.getData(1, conscriptldate.class);
		CurrencyHandle currencyHandle = new CurrencyHandle();
		Currency cost = Currency.create(costdata.getCosttype1(), costdata.getCostid1(), costdata.getCostnum1());
		try {
			currencyHandle.cost(playerCode, CCReason.主公府拜将, cost);
		} catch (CurrencyNotEnoughException e) {
			send(messageSource, response, new Result(Result.CostFail, e.getType().getNumber(), e.getDataId()));// 消费不足
			return;
		}
		OfficeHandle officeHandle = new OfficeHandle();

		Currency hero = officeHandle.summon(playerCode, type);
		if (hero == null) {
			send(messageSource, response, Result.ParamError);
			return;
		}

		ArrayList<Currency> rewards = new ArrayList<>();
		rewards.addAll(Currency.create(costdata.getGettype(), costdata.getGetid(), costdata.getGetnum()));
		rewards.add(hero);
		currencyHandle.addCurrency(playerCode, CCReason.主公府拜将, rewards);
		response.addAllItems(officeHandle.getItems(playerCode));
		response.addAllRewards(currencyHandle.packItems(rewards));
		send(messageSource, response, Result.Success);
		
		TaskHandle.handle(playerCode, TaskType.统计型_主公府_拜将_次数, 1);
	}

	private void send(MessageSource messageSource, OfficeMessage.OfficeSummonResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}